﻿using System;
using System.Collections.Generic;

using Gonte.Reflection;

namespace Gonte
{
    public static class ObjectComparer
    {
        /// <summary>
        /// Compares two objects for equality
        /// </summary>
        /// <param name="obj1">The first object</param>
        /// <param name="obj2">The second object</param>
        /// <param name="modifiedPropertyNames">The list of the name of the properties that are not equal</param>
        /// <returns>True if the objects are equal, otherwise returns false</returns>
        public static bool AreEqual(Object obj1, Object obj2, out List<string> modifiedPropertyNames)
        {
            modifiedPropertyNames = new List<string>();
            Type type = obj1.GetType();

            if (!type.Equals(obj2.GetType()))
            {
                return false;
            }

            TypeAccessor typeAccessor = TypeAccessor.GetTypeAccessor(type);

            foreach (string propertyName in typeAccessor.PropertyNames)
            {
                if (typeAccessor.IsPrimitive(propertyName))
                {
                    Object value1 = typeAccessor.GetValue(obj1, propertyName);
                    Object value2 = typeAccessor.GetValue(obj2, propertyName);

                    if (value1 != null
                        && !value1.Equals(value2)) // Different values
                    {
                        modifiedPropertyNames.Add(propertyName);
                    }
                }
            }

            return (modifiedPropertyNames.Count == 0); // The objects are equal when there are no differences
        }
    }
}
